import React, { useEffect, useRef, useState } from 'react';
import { View, StyleSheet, TouchableWithoutFeedback } from 'react-native';
import { useThemeColors, UI, Navigation, ToastService } from '@gaozh1024/rn-toolkit';

type DownloadModalParams = {
  title?: string;
  fileName?: string;
  fileSize?: string;
  autoStart?: boolean;
  maskClosable?: boolean;
  maskColor?: string;
};

const DownloadModal: React.FC<any> = ({ route }) => {
  const colors = useThemeColors();
  const params: DownloadModalParams = route?.params || {};
  const {
    title = '下载文件',
    fileName = '未知文件',
    fileSize = '',
    autoStart = false,
    maskClosable = true,
    maskColor = 'rgba(0,0,0,0.45)',
  } = params;

  const [progress, setProgress] = useState<number>(0);
  const [running, setRunning] = useState<boolean>(false);
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const start = () => {
    if (running) return;
    setRunning(true);
    ToastService.show({ message: '开始下载...' });
    timerRef.current = setInterval(() => {
      setProgress((p) => {
        const next = Math.min(100, p + 3);
        if (next >= 100) {
          clearInterval(timerRef.current as any);
          timerRef.current = null;
          setRunning(false);
          ToastService.show({ message: '下载完成' });
        }
        return next;
      });
    }, 120);
  };

  const cancel = () => {
    if (timerRef.current) {
      clearInterval(timerRef.current as any);
      timerRef.current = null;
    }
    setRunning(false);
    setProgress(0);
    ToastService.show({ message: '已取消下载' });
    Navigation.closeModal();
  };

  const close = () => {
    if (timerRef.current) {
      clearInterval(timerRef.current as any);
      timerRef.current = null;
    }
    setRunning(false);
    Navigation.closeModal();
  };

  useEffect(() => {
    if (autoStart) start();
    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current as any);
        timerRef.current = null;
      }
    };
  }, [autoStart]);

  const styles = StyleSheet.create({
    overlay: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
    },
    mask: {
      position: 'absolute',
      top: 0, left: 0, right: 0, bottom: 0,
      backgroundColor: maskColor,
    },
    card: {
      width: '88%',
      borderRadius: 12,
      borderWidth: 1,
      borderColor: colors.border,
      backgroundColor: colors.surface,
      padding: 16,
    },
    row: { gap: 12 },
  });

  return (
    <View style={styles.overlay}>
      <TouchableWithoutFeedback onPress={maskClosable ? close : undefined} testID="download_modal_mask">
        <View style={styles.mask} />
      </TouchableWithoutFeedback>

      <View style={styles.card} testID="download_modal">
        <UI.Text variant="h3" color="text" mb={6}>{title}</UI.Text>
        <UI.Text variant="body2" color="textSecondary" mb={2}>
          {fileName}{fileSize ? ` · ${fileSize}` : ''}
        </UI.Text>

        <View style={{ marginVertical: 12 }}>
          <UI.Progress variant="linear" value={progress / 100} trackColor={colors.border} />
          <UI.Text variant="caption" color="subtext" mt={8} testID="download_modal_progress_text">
            {progress}%
          </UI.Text>
        </View>

        <View style={styles.row}>
          {running ? (
            <UI.Button title="取消下载" onPress={cancel} fullWidth variant="outline" testID="download_modal_cancel_btn" />
          ) : progress >= 100 ? (
            <UI.Button title="关闭" onPress={close} fullWidth variant="primary" testID="download_modal_close_btn" />
          ) : (
            <UI.Button title="开始下载" onPress={start} fullWidth variant="primary" testID="download_modal_start_btn" />
          )}
        </View>
      </View>
    </View>
  );
};

export default DownloadModal;